<template>
  <div>
    <h5 class="text-muted">当前任务：项目调查</h5>
    <el-form class="query-form" @submit.native.prevent :inline="true" :model="params">
      <el-form-item>
        <el-input
          v-model="params.customer_name"
          :clearable="true"
          placeholder="企业名称查询"
          @change="getData"
        ></el-input>
      </el-form-item>

      <el-form-item>
        <el-checkbox
          v-model="params.has_ele_fee"
          v-show="!showImportBtn"
          border
          :true-label="1"
          false-label=""
          @change="getData"
        >
          有电表
        </el-checkbox>
      </el-form-item>
      <el-form-item>
        <el-checkbox
          v-model="params.has_camera"
          v-show="!showImportBtn"
          border
          :true-label="1"
          false-label=""
          @change="getData"
        >
          有摄像头
        </el-checkbox>
      </el-form-item>
      <el-form-item>
        <el-button @click="getData()" v-show="!showImportBtn">查询</el-button>
        <el-button @click="getOneIndustry" v-show="showImportBtn">查询</el-button>
      </el-form-item>
      <el-form-item class="float-right" style="margin-right: 50px" v-if="1">
        <el-badge :value="oneIndustryTotalCount" type="primary" class="item">
          <el-button class="btn-long" @click="getOneIndustryView" v-loading="loading">
            十二大产业贷
          </el-button>
        </el-badge>
      </el-form-item>
    </el-form>
    <loading-wrap>
      <el-table border :data="tableData" v-show="!showImportBtn">
        <el-table-column prop="customer_name" label="企业名称" min-width="180"></el-table-column>
        <el-table-column prop="address" label="地址" min-width="140">
          <template slot-scope="scope">
            <span class="text-truncate" :title="scope.row.address">{{ scope.row.address }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="org_class_name" label="组织形式" min-width="110"></el-table-column>
        <el-table-column label="企业类型">
          <template slot-scope="scope">
            {{ enumFarmType[scope.row.farm_type] }}
          </template>
        </el-table-column>

        <el-table-column prop="corp_name" label="法人"></el-table-column>
        <el-table-column label="联系电话" min-width="100">
          <template slot-scope="scope">
            <span>{{ scope.row.mobile_no }}</span>
          </template>
        </el-table-column>

        <el-table-column label="分配时间" min-width="85">
          <template slot-scope="scope">
            <span>{{ scope.row.taskAssginDate }}</span>
          </template>
        </el-table-column>

        <el-table-column label="调查完成时间" min-width="85">
          <template slot-scope="scope">
            <span>{{ scope.row.taskCompleteDate }}</span>
          </template>
        </el-table-column>

        <el-table-column label="完成天数" align="right">
          <template slot-scope="scope">
            <span>{{ scope.row.completeDays }}</span>
          </template>
        </el-table-column>

        <el-table-column label="申请金额(万元)" align="right">
          <template slot-scope="scope">
            <span>{{ scope.row.apply_funds }}</span>
          </template>
        </el-table-column>
        <el-table-column label="预审金额(万元)" align="right">
          <template slot-scope="scope">
            <span>{{ scope.row.approved_funds }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="apply_funds" label="数据采集" align="center">
          <template slot-scope="scope">
            <span :class="`text-${scope.row.projectStatusCss}`">
              {{ scope.row.projectStatusLabel }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="152">
          <template slot-scope="scope">
            <el-tooltip effect="dark" content="调查审批" placement="bottom">
              <el-button
                type="text"
                class="py-0 px-1"
                v-show="scope.row.approvalActionEnable"
                @click="onApproval(scope.row)"
              >
                <i class="fa fa-gavel"></i>
              </el-button>
            </el-tooltip>

            <el-tooltip effect="dark" content="数据采集及信用档案" placement="bottom">
              <el-button type="text" class="py-0 px-2" @click="goInfo(scope.row)">
                <i class="fa fa-edit"></i>
              </el-button>
            </el-tooltip>

            <el-tooltip effect="dark" content="附件" placement="bottom">
              <el-button type="text" class="py-0 px-1" @click="onAttach(scope.row)">
                <i class="fa fa-clipboard"></i>
              </el-button>
            </el-tooltip>

            <el-tooltip effect="dark" content="查看" placement="bottom">
              <el-button type="text" class="py-0 px-2" @click="goOutfo(scope.row)">
                <i class="fa fa-search"></i>
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <div class="query-pagination" v-show="!showImportBtn">
        <el-pagination
          @current-change="getData"
          :current-page.sync="params.index"
          :page-size="params.size"
          layout="total, prev, pager, next, jumper"
          :total="totalCount"
        ></el-pagination>
      </div>
      <el-table border :data="oneIndustryTableData" v-show="showImportBtn">
        <el-table-column label="借款人/担保客户" prop="customer_name"></el-table-column>
        <el-table-column label="客户类型" prop="org_class_name"></el-table-column>
        <el-table-column label="主营业务" prop="main_budiness"></el-table-column>
        <el-table-column label="联系电话" prop="corp_phone"></el-table-column>
        <el-table-column label="放款日/拟担保起始日">
          <template slot-scope="scope">
            <span>{{ $utils.dateFormat(scope.row.load_date, 'yyyy-MM-dd') || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="到期日">
          <template slot-scope="scope">
            <span>{{ $utils.dateFormat(scope.row.load_end_date, 'yyyy-MM-dd') || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="贷款期限" prop="warranty_period"></el-table-column>
        <el-table-column
          label="审批金额（万元）"
          prop="warranty_amount"
          align="right"
        ></el-table-column>
        <el-table-column label="审批状态">
          <template slot-scope="scope">
            {{ enumRepayInterest[scope.row.project_status] || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button class="py-0 px-2" type="text" @click="approvalReject(scope.row)">
              <i class="fa fa-edit"></i>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="query-pagination" v-show="showImportBtn">
        <el-pagination
          layout="total, prev, pager, next, jumper"
          :current-page.sync="params.index"
          :page-size="params.size"
          :total="oneIndustryTotalCount"
          @current-change="getOneIndustry"
        ></el-pagination>
      </div>
    </loading-wrap>

    <el-dialog
      :visible.sync="reportView"
      :close-on-click-modal="false"
      :before-close="closeReportView"
      top="30px"
      width="80%"
    >
      <el-tabs v-model="activeName">
        <el-tab-pane label="信用档案" name="first">
          <credit-file
            :view-mode="true"
            v-if="reportView"
            :related-id="customerRelatedId"
          ></credit-file>
        </el-tab-pane>

        <el-tab-pane label="调查报告" v-if="projectStatus" name="second">
          <!-- <prcatise :view-mode="true"
                    :related-id="customerRelatedId"></prcatise> -->
          <census-report :view-mode="true" :related-id="customerRelatedId"></census-report>
        </el-tab-pane>
        <el-tab-pane label="附件" name="third">
          <attach-list :data-list="dataList"></attach-list>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <attach-cmpt :visible.sync="attachVisible" :customer-related-id="attachRelatedId"></attach-cmpt>

    <el-dialog
      title="项目调查审核"
      :visible.sync="approvalVisible"
      width="420px"
      :close-on-click-modal="false"
    >
      <div class="dl-wrap mb-5" v-if="approvalSelectRow.is_simple_process !== '1'">
        <div class="dl-dt">是否需要评级</div>
        <div class="dl-dd">
          <el-radio-group v-model="approvalIsNeedRating">
            <el-radio :label="1">需要</el-radio>
            <el-radio :label="2">不需要</el-radio>
          </el-radio-group>
        </div>
      </div>

      <div>
        <el-button type="primary" class="btn-long" @click="onApprovalProject(3)">通过</el-button>
        <el-button type="danger" plain @click="onApprovalProject(2)">不通过</el-button>
      </div>
    </el-dialog>

    <c-form-dialog
      ref="productForm"
      :form-items="formItems"
      :form-data="formData"
      :table-name="formTable"
      :table-id="tableId"
      label-width="120px"
      @success="getOneIndustry"
      :visible.sync="formVisible"
    ></c-form-dialog>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import { deltaDay } from '@/common/plugins/tools/date'
import { arrayFromString } from '@vimi/utils-tool'
import { enumFarmType, enumDatumCollStatus } from '@/credit/plugins/enum'
import AttachCmpt from '@/credit/views/city/program/Attach'
import CreditFile from '@/credit/components/creditFile/Index'
import AttachList from './AttachList'
// import Prcatise from './Prcatise'
import CensusReport from '@/credit/views/city/task/CensusReport'
import { ONE_INDUSTRY_LOAD_PRODUCT } from '@/credit/plugins/constant'
const enumRepayInterest = {
  3: '通过',
  4: '不通过',
}
export default {
  components: {
    // Prcatise,
    CensusReport,
    CreditFile,
    AttachList,
    AttachCmpt,
  },
  props: {},
  data() {
    return {
      enumFarmType,
      enumDatumCollStatus,

      // 一县一业产业贷
      formVisible: false,
      tableId: '',
      formTable: 'datum_one_county_industry',
      formData: {},
      enumRepayInterest,
      formItems: [
        {
          tag: 'radio-group',
          itemAttrs: { label: '调查状态' },
          attrs: { clearable: false, key: 'is_pass', options: enumRepayInterest },
        },
        {
          tag: 'textarea',
          itemAttrs: { label: '不通过原因' },
          attrs: { key: 'not_pass_reason', value: '', placeholder: '请输入原因' },
        },
      ],
      showImportBtn: false,
      oneIndustryTotalCount: 0,
      oneIndustryTableData: [],
      params: {
        index: 1,
        size: 10,
        'task_status.eq': 1,
        customer_name: '',
        has_ele: '',
        has_camera: '',
      },
      totalCount: 0,
      tableData: [],
      checkData: [
        { name: '有电表', value: '有电表' },
        { name: '有摄像头', value: '有摄像头' },
      ],
      status: '',
      attachVisible: false,
      attachRelatedId: '',
      file: 0,
      customerRelatedId: '',
      reportView: false,
      activeName: 'first',
      dataList: [],
      ProjectStatus: 1,
      //
      approvalVisible: false,
      approvalSelectRow: {},
      approvalIsNeedRating: 1,
      approvalLoading: false,
      loading: false,
    }
  },
  computed: {
    projectStatus() {
      return this.ProjectStatus === 1 || this.ProjectStatus === 3
    },
    ...mapGetters(['user', 'org']),
    userId() {
      return this.user.userId
    },
    clientId() {
      return this.org.clientId
    },
    job() {
      return this.user.job
    },
  },
  watch: {
    $route(route) {
      if (route.name === 'taskSurvey') {
        this.status = this.$route.query.status
        if (this.status) {
          this.params['project_status.eq'] = this.status
        }

        this.showImportBtn = false
        this.getData()
        this.getOneIndustry()
      }
    },
  },
  created() {
    this.params['project_status.eq'] = this.$route.query.status
    this.params['service_id.eq'] = this.clientId
    this.getData()
    this.getOneIndustry()
  },
  activated() {},
  mounted() {},
  methods: {
    approvalReject(row) {
      this.formData = row || {}
      this.tableId = this.formData['customer_related_id'] || ''
      this.formVisible = true
    },
    closeReportView() {
      this.reportView = false
      this.getData()
    },

    onAttach(row) {
      this.attachRelatedId = row.customer_related_id
      this.attachVisible = true
    },

    getData() {
      const params = { ...this.params }
      const status = this.$route.query.status
      if (status !== undefined) {
        params['project_status.eq'] = status
      }

      params['loan_product_id.neq'] = ONE_INDUSTRY_LOAD_PRODUCT
      const taskStatus = this.$route.query.taskStatus
      if (taskStatus !== undefined) {
        params['task_status.eq'] = taskStatus
      }
      let job = this.$store.getters.user.job
      if (
        job !== 'org_credit_super' &&
        job !== 'org_c_manage' &&
        job !== 'org_r_emp' &&
        job !== 'org_r_manage' &&
        job !== 'org_corp'
      ) {
        params['orWhere.res_a.eq'] = this.userId
        params['orWhere.res_b.eq'] = this.userId
      }
      this.$api
        .getData('credit', 'customer_related_view', params, {
          create_time: 'desc',
        })
        .then(res => {
          if (res && res.data) {
            this.totalCount = res.data.totalCount || 0
            const data = res.data.data || []
            this.tableData = data.map(item => {
              // 数据采集状态
              const ps = enumDatumCollStatus[item.project_status] || {}
              item.projectStatusCss = ps.css || ''
              item.projectStatusLabel = ps.label || ''
              if (item.project_status === '1') {
                item.projectStatusCss = 'ondine'
              }

              // 完成天数
              item.taskAssginDate = this.$utils.dateFormat(item.task_assgin_date, 'yyyy.MM.dd')
              item.taskCompleteDate = this.$utils.dateFormat(item.task_complete_date, 'yyyy.MM.dd')
              const days = deltaDay(item.task_assgin_date, item.task_complete_date)
              item.completeDays = days ? `${days}天` : ''

              // 负责人调查审批按钮
              item.approvalActionEnable = this.job === 'org_c_manage' && item.project_status === '1'

              return item
            })
          } else {
            this.tableData = []
            this.totalCount = 0
          }
        })
      // this.getOneIndustry()
    },
    getOneIndustryView() {
      this.showImportBtn = !this.showImportBtn
    },

    getOneIndustry() {
      this.params.has_ele_fee = ''
      this.params.has_camera = ''
      if (this.params.has_ele || this.params.has_camera) {
        this.oneIndustryTotalCount = 0
        this.oneIndustryTableData = []
        return
      }
      this.$api
        .getData('credit', 'datum_one_county_industry', this.params, {
          N1project_status: 'asc',
          N2load_date: 'desc',
        })
        .then(res => {
          this.oneIndustryTableData = (res && res.data && res.data.data) || []
          this.oneIndustryTotalCount = (res && res.data && res.data.totalCount) || 0
        })
    },

    goInfo(data) {
      sessionStorage.setItem('customer_related_id', data.customer_related_id)
      sessionStorage.setItem('customer_related_view', JSON.stringify(data))
      sessionStorage.setItem('credit_task_router', 'survey')
      this.$router.push({
        path: '/credit/task/info',
        query: { id: data.customer_related_id },
      })
    },

    goOutfo(data) {
      sessionStorage.setItem('customer_related_id', data.customer_related_id)
      sessionStorage.setItem('customer_related_view', JSON.stringify(data))
      sessionStorage.setItem('credit_task_router', 'survey')
      this.getAttachment()
      this.file++
      this.customerRelatedId = data.customer_related_id
      this.ProjectStatus = +data.project_status
      this.reportView = true
    },

    getAttachment() {
      this.dataList = []
      this.$api
        .getData(
          'credit',
          'datum_customer_attachment',
          {
            'customer_related_id.eq': sessionStorage.getItem('customer_related_id'),
          },
          { create_time: 'desc' }
        )
        .then(res => {
          if (!res || !res.data) {
            return
          }
          for (let p of res.data) {
            const images = arrayFromString(p.attachment)
            this.dataList.push({
              src: images,
              time: this.$utils.dateFormat(p.create_time, 'yyyy.MM.dd'),
              name: p.attachment_type,
            })
          }
        })
    },

    onApproval(row) {
      this.approvalSelectRow = row
      this.approvalIsNeedRating = +row.is_need_rating || 1
      this.approvalVisible = true
    },

    async onApprovalProject(projectStatus) {
      const formData = {}
      if (this.approvalSelectRow.is_simple_process !== '1') {
        formData.is_need_rating = this.approvalIsNeedRating
      }
      formData.project_status = projectStatus

      this.approvalLoading = true
      const [res] = await this.$utils.promise(
        this.$api.updateData(
          'credit',
          'customer_related',
          this.approvalSelectRow.customer_related_id,
          formData
        )
      )
      this.approvalLoading = false

      if (!res) {
        return this.$message.error('操作失败，请重试！')
      }

      this.$message.success('操作成功！')
      this.getData()
      this.$store.dispatch('getTaskCount')
      this.approvalVisible = false
    },
  },
}
</script>
<style scoped>
.text-num {
  font-size: 1.25rem;
  font-weight: bold;
}
.text-ondine {
  color: #40e0d0;
}
</style>
